package com.estun.backroundManagementService.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.estun.backroundManagementService.domain.BaseResponse;
import com.estun.backroundManagementService.enums.WorkOrderStatusEnum;
import com.estun.backroundManagementService.modules.workOrder.dto.WorkOrderEntity;
import com.estun.backroundManagementService.modules.workOrder.service.WorkOrderService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yusiocng
 * @date 2023/12/19
 * @description 推送定时任务
 */

@Slf4j
@Component
@AllArgsConstructor
@Profile("prd")
public class SyncScheduleTask {

    private final WorkOrderService workOrderService;

    /**
     * 推送 完成排程
     */
    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void pushFinishedSchedule() {
        log.info("【排程状态同步】 任务开始----");
        //* 排程状态（0：新建，1、下达，2、开线，3、生产、4、暂停、5、取消、6、完成）
        //获取带完成排程 状态为生产 且 完成数量(finished) >=排程数量(qty) 相等
        //查询所有进行中的排程
        List<WorkOrderEntity> list = workOrderService.list(new QueryWrapper<WorkOrderEntity>()
                .eq("order_status", WorkOrderStatusEnum.IN_PRODUCTION.getCode())
        );
        if (CollectionUtils.isEmpty(list)) {
            log.info("【排程状态同步】当前不存在进行中排程,按时间排序查找排程 改为进行中");
            BaseResponse beginScheduleRes = workOrderService.autoBeginSchedule();
            log.info("【排程状态同步】启动排程结果：{}", beginScheduleRes);
        } else {
            List<WorkOrderEntity> finishedSchedule = list.stream()
                    .filter(workOrder -> workOrder.getScheduleQtyFinished() >= workOrder.getScheduleQty()).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(finishedSchedule)) {
                log.info("【排程状态同步】没有需要处理的排程");
            }
            for (WorkOrderEntity workOrderEntity : finishedSchedule) {
                BaseResponse baseResponse = workOrderService.updateScheduleStatus(workOrderEntity, WorkOrderStatusEnum.COMPLETED);
                log.info("【排程状态同步】排程更新结果:{}", baseResponse);
            }
        }
        log.info("【排程状态自动更新与推送 定时任务】 任务结束----");
    }


}
